package models;

import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import play.*;
import play.db.jpa.*;

import javax.persistence.*;
import java.util.*;

@Entity
public class Circle extends Model {
	
	public String name;
	
	public String company;
	public String location;
	
	public Date createDate;
	
	public double lat;
	public double lng;
	
	public Blob photo;
	public Blob map;
	
	@ManyToOne
	public User founder;
	
	@ManyToMany
	public Set<User> members;
	
	@ManyToMany
	public Set<Tag> tags;
	
	@ManyToMany(mappedBy="notifiedCircles")
	public Set<Post> posts;

	public Circle(String name, String company, String location, double lat, double lng, Long uid) {
		User u = User.findById(uid);
		this.name = name;
		this.company = company;
		this.location = location;
		this.createDate = new Date();
		this.lat = lat;
		this.lng = lng;
		this.tags = new HashSet<Tag>();
		this.members = new HashSet<User>();
		this.founder = u;
	}
	
	public boolean distroyMap() {
		if(this.hasMap()) {
			return this.map.getFile().delete();
		}
		return true;
	}
	
	public boolean hasMap() {
		if(this.map != null) {
			if(this.map.exists()) {
				return true;
			}
		}
		return false;
	}
	
	public boolean hasPhoto() {
		if(this.photo != null) {
			if(this.photo.exists()) {
				return true;
			}
		}
		return false;
	}
	
	public boolean addTag(String tagName) {
		Tag t = Tag.find("byName", tagName).first();
		if (t == null) {
			Tag nt = new Tag(tagName);
			if (this.tags.add(nt)) {
				if (nt.circlesWithTag.add(this)) {
					nt.qty++;
					nt.save();
					this.save();
					return true;
				}
			}
			return false;
		} else {
			if (this.tags.add(t)) {
				if (t.circlesWithTag.add(this)) {
					t.qty++;
					t.save();
					this.save();
					return true;
				}
			}
			return false;
		}
	}
	
	public boolean addMember(Long uid) {
		User u = User.findById(uid);
		if(u != null) {
			this.members.add(u);
			u.circles.add(this);
			u.save();
			this.save();
			return true;
		}
		return false;
	}
	
	public String getTagsString() {
		String result = "";
		Iterator i = this.tags.iterator();
		while(i.hasNext()) {
			Tag t = (Tag)i.next();
			result = result + t.name + ",";
		}
		return result;
	}
	
	public String getPostNumber() {
		Integer i = 0;
		Iterator n = this.posts.iterator();
		while(n.hasNext()) {
			n.next();
			i++;
		}
		return i.toString();
	}
	
	public String getMemberNumber() {
		Integer i = 0;
		Iterator n = this.members.iterator();
		while(n.hasNext()) {
			n.next();
			i++;
		}
		return i.toString();
	}
	
}